package com.rp.system.dao;

import java.util.List;

import org.raptor.common.DbOperUtil;
import org.raptor.orm.hibernate.DbaHibernateTemplateSupport;
import org.raptor.pagination.Page2;
import org.springframework.stereotype.Repository;

import com.rp.common.utils.RpUtil;
import com.rp.common.vo.PageParam;
import com.rp.system.po.User;
import com.rp.system.vo.UserVo;

@Repository
public class UserDao extends DbaHibernateTemplateSupport<User>{
	
	/**
	 * 根据用户名获取用户
	 * @param username
	 * @return
	 */
	public User getUserByUsername(String username){
		String hql = "from User where username = ?";
		List<User> users = this.find(hql, username);
		if(users.size() != 0){
			return users.get(0);
		}
		return null;
	}
	
	/**
	 * 根据用户名和密码获取用户
	 * @param username
	 * @param password
	 * @return
	 */
	public User getUserByUsernameAndPassword(String username, String password){
		String hql = "from User where username = ? and password = ?";
		List<User> users = this.find(hql, username, RpUtil.md5Encrypt(password));
		if(users.size() != 0){
			return users.get(0);
		}
		return null;
	}
	
	/**
	 * 分页获取用户数据
	 * @param userVo
	 * @return
	 */
	public Page2 getUsersByPage(PageParam pageParam, UserVo userVo){
		
		String hql = "";
		Page2 page = null;
		
		if(userVo.getOrganId().equals("")){
			hql = "from User where username like ? and realname like ? and superAdmin = '0'";
			page = this.getPage2ByOffset(hql, 
					pageParam.getPageOffset(), pageParam.getPageSize(),
					pageParam.getSortField(), pageParam.getSortOrder(), 
					DbOperUtil.fuzzyQueryParam(userVo.getUsername()), 
					DbOperUtil.fuzzyQueryParam(userVo.getRealname()));
		}else{
			hql = "from User where username like ? and realname like ? and organId like ? and superAdmin = '0'";
			page = this.getPage2ByOffset(hql, 
					pageParam.getPageOffset(), pageParam.getPageSize(),
					pageParam.getSortField(), pageParam.getSortOrder(), 
					DbOperUtil.fuzzyQueryParam(userVo.getUsername()), 
					DbOperUtil.fuzzyQueryParam(userVo.getRealname()),
					DbOperUtil.fuzzyQueryParam(userVo.getOrganId()));
		}
		return page;
	}
	
}
